package com.artpri.service.impl;

import java.util.Map;

import org.springframework.transaction.annotation.Transactional;

import com.artpri.model.UserInfo;
import com.artpri.service.UserService;
import com.artpri.util.DataValidator;
import com.artpri.util.Md5Util;
import com.artpri.util.TimeUtil;

/**
 * user -service
 * @author ZhangSi
 */
public class UserServiceImpl extends BaseService implements UserService{
	
	private String getMd5Pwd(Integer userNum, String passwd) {
		return Md5Util.getMD5String(Md5Util.getMD5String(passwd) + userNum);
	}
	
	@Override
	@Transactional(readOnly=true)
	public boolean login(String user, String pass, Map<String, Object> session) {
		UserInfo userInfo = null;
		
		if (DataValidator.isMobileNo(user)) {
			userInfo = getUserInfoDao().getUserByMobile(user);
		}else if(DataValidator.isEmail(user)) {
			userInfo = getUserInfoDao().getUserByEmail(user);
		}
		
		if(userInfo != null) {
			boolean b = userInfo.getUserPasswd().equals(getMd5Pwd(userInfo.getUserNum(), pass));
			if (b) {
				session.put("user", userInfo);
				return true;
			} else {
				return false;
			}
		}
		return false;
	}

	@Override
	@Transactional(readOnly=true)
	public boolean keepLogin(String lName, String lPass, Map<String, Object> session) {
		
		UserInfo userInfo = null;
		
		if (DataValidator.isMobileNo(lName)) {
			userInfo = getUserInfoDao().getUserByMobile(lName);
		}else if(DataValidator.isEmail(lName)) {
			userInfo = getUserInfoDao().getUserByEmail(lName);
		}
		
		if (userInfo != null) {
			boolean b = userInfo.getUserPasswd().equals(getMd5Pwd(userInfo.getUserNum(), lPass));
			if (b) {
				session.put("user", userInfo);
				return true;
			} else {
				return false;
			}
		}
		return false;
	}
	
	@Override
	public void logout(Map<String, Object> session) {
		session.remove("user");
	}

	@Override
	@Transactional
	public String emailRegist(UserInfo user) {
		user.setUserRegTime(TimeUtil.getTimeStamp());
		
		// 对密码加密加盐
		String secPwd = Md5Util.getMD5String(Md5Util.getMD5String(user.getUserPasswd()) + user.getUserNum());
		user.setUserPasswd(secPwd);
		
		// 激活码
		String activateCode = Md5Util.getMD5String(user.getUserEmail());
		
		user.setUserStatus(activateCode);
		
		getUserInfoDao().save(user);
		
		return activateCode;
	}

	@Override
	@Transactional
	public boolean activateUser(Integer id, String data) {
		UserInfo user = getUserInfoDao().get(UserInfo.class, id);
		if (user != null) {
			if (user.getUserStatus().equals(data)) {
				user.setUserStatus("1");
				return true;
			} else if (user.getUserStatus().equals("1")){
				return true;
			} else {
				return false;
			}
		} else {
			return false;
		}
	}

	@Override
	@Transactional(readOnly=true)
	public boolean checkUserNameExists(String name) {
		Integer i = getUserInfoDao().checkUserNameExists(name);
		return i == null || i == 0 ? false : true;
	}

}
